#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <locale.h>
#define MAX_INPUT_LEN 128
#define SECONDS_PER_MINUTE 60
#define SECONDS_PER_HOUR 3600

int main() {
    // 设置控制台代码页为 65001 (UTF-8)，防止乱码
    system("chcp 65001 > nul");
    // 使用宽字符API设置控制台标题
    SetConsoleTitleW(L"时间转换程序   编写：王康");

    char condition;
    do {
        long num;
        int validInput;
        do {
            printf("\033[32m请输入一个秒数(正整数)：\033[0m");
            validInput = scanf("%ld", &num);
            // 清空输入缓冲区
            while (getchar() != '\n');
        } while (validInput != 1 || num <= 0);

        long time[3];
        //转成小时和分钟
        int hour = num / SECONDS_PER_HOUR;
        int minute = num / SECONDS_PER_MINUTE;
        time[0] = hour;
        time[1] = minute - hour * SECONDS_PER_MINUTE;
        time[2] = num % SECONDS_PER_MINUTE;
        printf("\033[35m转换后为：");
        if (time[0] > 0) {
            printf("\033[31m%d小时", time[0]);
        }
        if (time[1] > 0) {
            printf("\033[33m%d分钟", time[1]);
        }
        printf("\033[34m%d秒\033[0m\n", time[2]);
        printf("请输入(Y/y)继续，其他任意键退出：");
        int size = scanf(" %c", &condition);
        // 如果输入是回车键（'\n'），则退出循环
        if (size != 1 || condition == '\n') {
            condition = 'N'; // 设置为非 'Y' 的值以退出循环
        }
        else {
            condition = toupper(condition); // 将输入转换为大写
        }
    } while (condition == 'Y');
    return 0;
}

int main2() {
    char input[MAX_INPUT_LEN];
    printf("请输入一个整数: ");

    if (fgets(input, sizeof(input), stdin) == NULL) {
        fprintf(stderr, "读取输入失败\n");
        return EXIT_FAILURE;
    }
    input[strcspn(input, "\n")] = '\0';

    if (input[0] == '\0') {
        fprintf(stderr, "错误：输入为空\n");
        return EXIT_FAILURE;
    }

    char *endptr;
    long value;
    int sign = 1;

    endptr = input;
    while (isspace((unsigned char)*endptr)) endptr++;

    if (*endptr == '+' || *endptr == '-') {
        sign = (*endptr++ == '-') ? -1 : 1;
    }

    errno = 0;
    long temp = strtol(endptr, &endptr, 10);

    if (errno == ERANGE) {
        fprintf(stderr, "错误：数值超出long范围\n");
        return EXIT_FAILURE;
    }

    if (*endptr != '\0') {
        char *invalid_char = endptr;
        while (*invalid_char != '\0') {
            if (!isspace((unsigned char)*invalid_char)) {
                fprintf(stderr, "错误：包含非法字符 '%c' (ASCII %d)\n",
                    *invalid_char, *invalid_char);
                return EXIT_FAILURE;
            }
            invalid_char++;
        }
    }

    if (sign == 1 && temp > LONG_MAX) {
        fprintf(stderr, "错误：正数超出long最大值 %ld\n", LONG_MAX);
        return EXIT_FAILURE;
    }
    if (sign == -1 && temp < LONG_MIN) {
        fprintf(stderr, "错误：负数超出long最小值 %ld\n", LONG_MIN);
        return EXIT_FAILURE;
    }

    value = sign * temp;
    printf("转换成功：%ld\n", value);
    return EXIT_SUCCESS;
}
